import type { CustomRequestOptions } from '@/utils/http/requestInterceptor';
import { ResultCodeEnum } from '@/enums';
import { refreshToken } from '@/api/user';
import { useUserStore } from '@/store';
import { http } from '@/utils/http';

export const useHttpResolve = async <T>(
  res: UniApp.RequestSuccessCallbackResult,
  resolve: Function,
  options: CustomRequestOptions
) => {
  type TQueue = {
    config: CustomRequestOptions;
    resolve: Function;
  };

  let refreshing = false;
  let queue: TQueue[] = [];

  console.log('打印***res', res);
  if (res.statusCode >= 200 && res.statusCode < 300) {
    resolve(res.data as IResData<T>);
  } else if (res.statusCode === 401 && !options.url.includes('refreshToken')) {
    queue.push({
      config: options,
      resolve
    });
    if (refreshing) {
      return;
    }
    // 401错误  -> 刷新token，清理用户信息，跳转到登录页
    refreshing = true;
    const { code, data } = await refreshToken({
      refreshToken: useUserStore().userInfo.refreshToken
    });
    refreshing = false;
    if (code === ResultCodeEnum.SUCCESS) {
      useUserStore().setUserInfo({
        ...useUserStore().userInfo,
        accessToken: data.accessToken,
        refreshToken: data.refreshToken
      });

      try {
        queue.forEach((queueItem) => {
          queueItem.resolve(http(queueItem.config));
        });
        queue = [];
      } catch (error) {
        console.log('打印***error', error);
        queue = [];
      }
    } else {
      useUserStore().clearUserInfo();
      // 登陆后跳转
      const pages = getCurrentPages();
      let redirect_url = '/pages/center/index';
      console.log('打印***pages', pages);
      if (pages.length) {
        redirect_url =
          encodeURIComponent(
            (pages[pages.length - 1] as any)?.$page?.fullPath
          ) || '/pages/center/index';
        console.log('打印***redirect_url', redirect_url);
      }
      uni.navigateTo({
        url: `/pages/center/login/index?redirect_url=${redirect_url}`
      });
    }
    resolve({ code: 1, data: res as any, message: '请求错误' });
  } else if (res.statusCode === 403) {
    uni.showToast({
      icon: 'none',
      title: '其他地方已登录'
    });
    useUserStore().clearUserInfo();
    resolve({
      code: 1,
      data: res as any,
      message: '请求错误'
    });
  } else {
    uni.showToast({
      icon: 'none',
      title: (res.data as IResData<T>).message || '请求错误'
    });
    resolve({
      code: 1,
      data: res as any,
      message: '请求错误'
    });
  }
};

export const useHttpFail = (
  resolve: Function,
  err: UniApp.GeneralCallbackResult
) => {
  console.log('打印***err', err);
  uni.showToast({
    icon: 'none',
    title: '网络错误，换个网络试试'
  });
  resolve({
    code: 1,
    data: err as any,
    message: '网络错误，换个网络试试'
  });
};
